<?php
/**
 * Project  	Newsletter for Joomla 1.5.x
 * Release    	2.0.1
 * @package		Communicator
 * @subpackage	Component
 * @version		$Id$
 * @link 		http://joomlacode.org/gf/project/communicator/
 * @copyright	Copyright (c) 2008 Stefan Granholm, Copyright 2009 Erik Damke - All rights reserved
 * @license		http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
 *
 * @Author     Stefan Granholm (http://www.granholmcms.com), Erik Damke (commqc20@jocoflex.com)
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

// load the html drawing class, MUST include the option for components
require_once( JPATH_COMPONENT.DS.'communicator.html.php');
require_once( JPATH_COMPONENT.DS.'communicator.class.php');
// load Version Class for this Communicator instance
require_once( JPATH_COMPONENT_ADMINISTRATOR.DS.'version.communicator.php');

// Load configuration in constructor
$database =& JFactory::getDBO();
$communicator = new josCommunicator($database);

$document =& JFactory::getDocument();
$document->addStyleSheet('components/com_communicator/assets/communicator.css');
/* END CONFIG */

$access  = !$mainframe->getCfg( 'shownoauth' );
$task 	= JRequest::getVar( 'task', '');
$id 	   = JRequest::getInt( 'id', 0 ) ;
$user    =& JFactory::getUser();
$Itemid  = JRequest::getInt('Itemid', 0);
$option  = JRequest::getVar( 'option', '?' );
$subscriber_name = JRequest::getVar( 'subscriber_name', '');
$subscriber_email = JRequest::getVar( 'subscriber_email', '');
$limit 		= JRequest::getInt( 'limit', $mainframe->getCfg('list_limit') ) ;
$limitstart = JRequest::getInt( 'limitstart', 0 ) ;

if ($option == '?')     // indefined ?
   {
   $option = 'com_communicator';
   JRequest::setVar( 'option', $option );
   }

if ($Itemid == 0)
   {  
   $database->setQuery ( 'SELECT id FROM `#__menu`'.
            ' WHERE link LIKE \'%com_communicator%\'');
   $myid = $database->loadObject();
   $Itemid = (!empty($myid->id)) ? $myid->id : 1;      
   JRequest::setVar( 'Itemid', $Itemid );      
   }   

$communicator_rights = Array();
// Editor usertype check
$communicator_rights['is_editor'] = $is_editor = (strtolower($user->usertype) == 'editor' || strtolower($user->usertype) == 'publisher' || strtolower($user->usertype) == 'administrator' || strtolower($user->usertype) == 'super administrator' );
// Sender usertype check
$communicator_rights['is_sender'] = (strtolower($user->usertype) == 'manager' || strtolower($user->usertype) == 'administrator' || strtolower($user->usertype) == 'super administrator' );
// Who can delete?
$communicator_rights['can_delete'] = (strtolower($user->usertype) == 'administrator' || strtolower($user->usertype) == 'super administrator' );


HTML_communicator::header();

switch ($task) {
	case 'view':
		viewNewsletter( $id, $user->gid, $is_editor );		
		break;

	case 'edit':
		if( $communicator_rights['is_editor'] )
			editNewsletter( $id );
		break;

	case 'save':
		if( $communicator_rights['is_editor'] )
			saveNewsletter( );
		break;

	case 'cancel':
		if( $communicator_rights['is_editor'] )
			cancelNewsletter( );
		break;

	case 'sendNow':
		if( $communicator_rights['is_sender'] ) {
			HTML_communicator::send_bar( $id );
			cm_sendNewsletter( $id );
		}
		break;

	case 'sendMail':
		if( $communicator_rights['is_sender'] )
			cm_sendMail();
		break;

	case 'remove':
		if( $communicator_rights['can_delete'] )
			removeNewsletter( $id );
		break;

	case 'subscribe':
		HTML_communicator::subscribeSubscriber( );
		break;

	case 'unsubscribe';
		HTML_communicator::unsubscribeSubscriber( );
		break;

	case 'confirm':
		confirmSubscriber( );
		break;

	default:
		global $cm_params;
		
		// get a menu item based on Itemid 
      $menu = &JSite::getMenu();
      $menu_parms = &$menu->getParams($Itemid);
      
      // copy the Page title settings
      $cm_params->set('page_title', $menu_parms->get('page_title'));
      $cm_params->set('show_page_title', $menu_parms->get('show_page_title'));
		
		HTML_communicator::defaultHeaderOpen();
		if ($cm_params->get( 'subscribe_button', 1 ))
			{
			HTML_communicator::subscriber_bar();
			}
		if( $communicator_rights['is_editor'] ) {
			HTML_communicator::new_bar();
		}
		HTML_communicator::defaultHeaderClose();
		listAll( $communicator_rights );

}

HTML_communicator::footer();

/* end of execution */

/*
 * Check if we got a valid email address
 */
function cm_email_check($email)
{   
	// First, we check that there's one @ symbol, and that the lengths are right
	if (!ereg("[^@]{1,64}@[^@]{1,255}", $email)) {
		// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
		return false;
	}
	// Split it into sections to make life easier
	$email_array = explode("@", $email);
	$local_array = explode(".", $email_array[0]);
	for ($i = 0; $i < sizeof($local_array); $i++) {
		if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
		   return false;
		}
	}
	if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
		$domain_array = explode(".", $email_array[1]);
		if (sizeof($domain_array) < 2) {
		   return false; // Not enough parts to domain
		}
		for ($i = 0; $i < sizeof($domain_array); $i++) {
			if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
			   return false;
			}
		}
	}
	return true;
}

function extended_email_check( $email )
{
	$config    =& JFactory::getConfig();

	require_once( JPATH_COMPONENT_ADMINISTRATOR.DS.'includes'.DS.'email_validation.php');
	$validator =& new email_validation_class();
	$localdata = parse_url( JURI::base() );
	$tmp 		  = explode( '@', $config->getValue('config.mailfrom') );
	$mailuser  = $tmp[0];
	$mailserver= $tmp[1];

	/* how many seconds to wait before each attempt to connect to the
	 destination e-mail server */
	$validator->timeout=10;

	/* how many seconds to wait for data exchanged with the server.
	 set to a non zero value if the data timeout will be different
	 than the connection timeout. */
	$validator->data_timeout=0;

	/* user part of the e-mail address of the sending user
	 (info@phpclasses.org in this example) */
	$validator->localuser=$mailuser;

	/* domain part of the e-mail address of the sending user */
	$validator->localhost=$mailserver;

	/* Set to 1 if you want to output of the dialog with the
	 destination mail server */
	$validator->debug=0;

	/* Set to 1 if you want the debug output to be formatted to be
	 displayed properly in a HTML page. */
	$validator->html_debug=1;


	/* When it is not possible to resolve the e-mail address of
	 destination server (MX record) eventually because the domain is
	 invalid, this class tries to resolve the domain address (A
	 record). If it fails, usually the resolver library assumes that
	 could be because the specified domain is just the subdomain
	 part. So, it appends the local default domain and tries to
	 resolve the resulting domain. It may happen that the local DNS
	 has an * for the A record, so any sub-domain is resolved to some
	 local IP address. This  prevents the class from figuring if the
	 specified e-mail address domain is valid. To avoid this problem,
	 just specify in this variable the local address that the
	 resolver library would return with gethostbyname() function for
	 invalid global domains that would be confused with valid local
	 domains. Here it can be either the domain name or its IP address. */
	$validator->exclude_address="";

	$result = $validator->ValidateEmailBox($email);

	return $result;
}

function listAll( $communicator_rights )
{
	global $mainframe;

	$database =& JFactory::getDBO();
	$Itemid = JRequest::getInt('Itemid');
	$option = JRequest::getVar('option');	
	$gid 	  = JRequest::getVar('gid');
	$user   =& JFactory::getUser();

	/* no longer requried as we use menuparms-title
	$database->setQuery ( 'SELECT name FROM `#__menu`'.
            ' WHERE id='.$Itemid );
   $menuname = $database->loadResult();
   */
	$menuname = '&nbsp;';        // just an empty title
   
	$limit = $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
	$limitstart = $mainframe->getUserStateFromRequest( $option.'limitstart', 'limitstart', 0, 'int' );
	$now = JHTML::_('date', 'now', '%Y-%m-%d %H:%M:%S' );

	$sql = 'SELECT id, subject, send, hits FROM `#__communicator`'.
			' WHERE ';
	if( !$communicator_rights['is_editor'] )
		$sql .= ' published=1 AND';

	$sql .= "\naccess <= $user->gid ";
	if( !$communicator_rights['is_editor'] ) {
		$sql .= "\nAND (publish_up = '0000-00-00 00:00:00' OR publish_up <= '$now') ";
		$sql .= "\nAND (publish_down = '0000-00-00 00:00:00' OR publish_down >= '$now')";
	}

	$database->setQuery( $sql );
	$database->query();
	$num_rows = $database->getNumRows();

	jimport('joomla.html.pagination');
	$pageNav = new JPagination( $num_rows, $limitstart, $limit );

	$sql .= ' ORDER BY created DESC';
	$sql .= ' LIMIT '.$limitstart.','.$limit;
	$database->setQuery( $sql );

	$newsletters = $database->loadObjectList();

	echo $database->getErrorMsg();
	HTML_communicator::listAll( $menuname , $newsletters, $communicator_rights, $pageNav );
}

function viewNewsletter( $uid, $gid, $is_editor )
{
	global $mainframe;

	$database  =& JFactory::getDBO();
	$user      =& JFactory::getUser();

	$now = JHTML::_('date', 'now', '%Y-%m-%d %H:%M:%S' );

	if ($is_editor) {
		$xwhere='';
	}
	else {
		$xwhere = ''.
			' AND published=1 '.
		 	"\n	AND (publish_up = '0000-00-00 00:00:00' OR publish_up <= '$now')".
		 	"\n	AND (publish_down = '0000-00-00 00:00:00' OR publish_down >= '$now')";
	}

	$sql = 'SELECT id, subject AS title, send, created, hits, html_message AS text'.
			' FROM #__communicator'.
			"\nWHERE id=$uid $xwhere".
			"\nAND access <= $gid ".
			' ORDER BY created DESC';
	$database->setQuery( $sql );
	$row = null;
	if ($row = $database->loadObject()) {

		$item = new josCommunicator($database);
		$item->hit( $row->id );
		if( $user->id > 0) {
			$row->text = str_replace( '[NAME]', $user->name, $row->text );
		}
		HTML_communicator::viewNewsletter( $row );

	}
	else {
		echo JText::_('You are not authorized to view this item');
		return;
	}
}

function saveSubscriber($name, $email)
{
	global $mainframe, $cm_params;

	$database =& JFactory::getDBO();
	$Itemid = JRequest::getInt('Itemid');
	$option = JRequest::getVar('option');
	$user   =& JFactory::getUser();
	$config =& Jfactory::getConfig();
	// Added to prevent spamming
	cm_SpoofCheck(NULL,1);

	$name 	= addslashes(strip_tags($name));
	$email 	= addslashes(strip_tags($email));

	if( $cm_params->get( 'extended_email_validation', '0') && function_exists('getmxrr'))
      {
		if( !extended_email_check( $email ) )
         {
			$mainframe->redirect( 'index.php?option='.$option.'&task=subscribe&Itemid='.$Itemid,
									JText::_('CM_VALID_EMAIL_PLEASE'));
		}
	else
		if (!cm_email_check($email))
		   {
			$mainframe->redirect( 'index.php?option='.$option.'&task=subscribe&Itemid='.$Itemid,
									JText::_('CM_VALID_EMAIL_PLEASE'));
		}
	}

	$row = new josCommunicatorSubscribers( $database );

	// load the row from the db table
	$row->subscriber_id = "";
	$row->user_id 	     = $user->id;
	$row->subscriber_name = $name;
	$row->subscriber_email = $email;
	$row->subscribe_date = date( "Y-m-d H:i:s" );

	if (!$row->store()) {
      echo "<script type=\"text/javascript\"> alert('".JText::_('CM_SAME_EMAIL_TWICE')."'); window.history.go(-1); </script>\n";
	}
	else {
		$subscriberhash = md5($database->insertid());
		$subject = str_replace( "[mosConfig_live_site]", JURI::root(), JText::_('CM_SUBSCRIBE_SUBJECT'));
		$confirmlink = JURI::root().'index.php?option='.$option.'&task=confirm&subscriber='.$subscriberhash;
		$content = str_replace( "[LINK]", $confirmlink, JText::_('CM_SUBSCRIBE_MESSAGE') );
		if( $user->id ) {
			$content = str_replace( "[NAME]", $user->name, $content );
		}
		else {
			$content = str_replace( "[NAME]", $name, $content );
		}
		$content = str_replace( "[mosConfig_live_site]", JURI::base(), $content );

		$fromMail = $cm_params->get( 'fromNlEmail', '');
		$fromName = $cm_params->get( 'fromNlName', '');
      if ($fromMail == '') {
		    $fromMail = $config->getValue('config.mailfrom');
		}
		if ($fromName == '') {
		    $fromName = $config->getValue('config.fromname');
		}
      $send = false;
		if( !$send = JUtility::sendMail( $fromMail, $fromName, $email, $subject, $content) )
         {
			echo '<script type="text/javascript">alert("'.JText::_('CM_ERROR_SENDING_SUBSCRIBE'). $send . '");</script>';
		   }
		$mainframe->redirect( 'index.php?option='.$option.'&Itemid='.$Itemid,
								    JText::_('CM_SUCCESS_SUBSCRIBE'));
	}
}

function deleteSubscriber( $name, $email )
{
	global $mainframe, $cm_params;

	$database =& JFactory::getDBO();
	$Itemid = JRequest::getInt('Itemid');
	$option = JRequest::getVar('option');
	$user   =& JFactory::getUser();
	$config =& Jfactory::getConfig();
	cm_SpoofCheck(NULL,1);

	$check = 'SELECT user_id FROM #__communicator_subscribers';
	if( $name != '') {
		$check .= ' WHERE subscriber_name = '.$database->Quote($name).
		          ' AND subscriber_email = '.$database->Quote($email);
	}
	else {
		$check .= ' WHERE subscriber_email = '.$database->Quote($email);
	}
	$database->setQuery( $check );
	$result = $database->loadObject();

	if( !$result ) {
		$mainframe->redirect( 'index.php?option='.$option.'&Itemid='.$Itemid,
								JText::_('E-mail address cannot be found') );
	}
	else {
		$query = 'DELETE FROM #__communicator_subscribers';
		if( $name != "" )
			$query .= ' WHERE subscriber_name  = '.$database->Quote($name).
					 	' AND subscriber_email = '.$database->Quote($email);
		else
			$query .= ' WHERE subscriber_email = '.$database->Quote($email);
		$database->setQuery($query);
		$database->query();

		$subject = str_replace( "[mosConfig_live_site]", JURI::base(), JText::_('CM_UNSUBSCRIBE_SUBJECT') );
		$content = str_replace( "[NAME]", $name, JText::_('CM_UNSUBSCRIBE_MESSAGE') );
		$content = str_replace( "[mosConfig_live_site]", JURI::base(), $content );

		$fromMail = $cm_params->get( 'fromNlEmail', '');
      $fromName = $cm_params->get( 'fromNlName', '');
      if ($fromMail == '') {
          $fromMail = $config->getValue('config.mailfrom');
      }
      if ($fromName == '') {
          $fromName = $config->getValue('config.fromname');
      }
		$send = false;
		if( !$send = JUtility::sendMail($fromMail, $fromName, $email, $subject, $content) ) {
			echo '<script type="text/javaScript">alert("'.JText::_('CM_ERROR_SENDING_UNSUBSCRIBE') . $send . '");</script>';
		}

		$mainframe->redirect( 'index.php?option='.$option.'&Itemid='.$Itemid,
								 JText::_('CM_SUCCESS_UNSUBSCRIBE'));
	}
}

function confirmSubscriber( )
{
	global $mainframe;

	$database  =& JFactory::getDBO();
	$Itemid    = JRequest::getInt('Itemid');
   $option    = JRequest::getVar('option');
	$subscriber= JRequest::getVar( 'subscriber', '');	
	$subscriber= addslashes(strip_tags($subscriber));

	$database->setQuery( "SELECT confirmed FROM #__communicator_subscribers WHERE md5(subscriber_id) = '" . $subscriber . "'" );
	$result = $database->loadObject();

	if( $result ) {
		$query = "UPDATE #__communicator_subscribers SET confirmed = 1 WHERE md5(subscriber_id) = '" . $subscriber . "'";
		$database->setQuery($query);
		$database->query();
		$mainframe->redirect( 'index.php?option='.$option.'&Itemid='.$Itemid,
								JText::_('CM_SUCCESS_CONFIRMATION'));
	}
	else {
		$mainframe->redirect( 'index.php?option='.$option.'&Itemid='.$Itemid,
								JText::_('CM_ERROR_CONFIRM_ACC_NOTFOUND'));
	}
}

function editNewsletter( $uid )
{
	global $mainframe;
	$database=& JFactory::getDBO();
	$user    =& JFactory::getUser();
	$Itemid  =& JRequest::getInt('Itemid');
   $option  = JRequest::getVar('option');
	$row = new josCommunicator( $database );
	// load the row from the db table
	$row->load( $uid );

	if( !empty($row->checked_out)) {
		if( $row->checked_out != $user->id )
			$mainframe->redirect( 'index.php?option='.$option.'&Itemid='.$Itemid,
									 JText::_('You are not authorized to view this item'));
	}

	if ($uid) {
		$row->checkout( $user->id );
	} else {
		// initialise new record
		$row->published = 0;
	}

	// make the select list for the image positions
	$yesno[] = JHTML::_( 'select.option', '0', 'No' );
	$yesno[] = JHTML::_( 'select.option', '1', 'Yes' );

	// build the html select list
	$publist = JHTMLSelect::genericlist( $yesno, 'published', 'class="inputbox" size="2"',
                                    	  'value', 'text', $row->published );

	// get list of groups
	$database->setQuery( 'SELECT id AS value, name AS text FROM #__groups ORDER BY id' );
	$groups = $database->loadObjectList();	if (!($orders = $database->loadObjectList())) 
      {
      echo $database->stderr();
	   return false;
	   }

	// build the html select list
	$glist = JHTMLSelect::genericlist( $groups, 'access', 'class="inputbox" size="1"',
										           'value', 'text', intval( $row->access ) );


	HTML_communicator::editNewsletter( $row, $publist, $glist );
}

function saveNewsletter( )
{
	global $mainframe;
	$database  =& JFactory::getDBO();
	$Itemid    = JRequest::getInt('Itemid');
	$option    = JRequest::getVar('option');

	$row = new josCommunicator( $database );

	if (!$row->bind( $_POST )) {
		echo "<script type=\"text/javascript\"> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	if (!$row->check()) {
		echo "<script type=\"text/javascript\"> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	if (!$row->store()) {
		echo "<script type=\"text/javascript\"> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	$row->checkin();

	$mainframe->redirect( 'index.php?option='.$option.'&Itemid='.$Itemid,
							JText::_('E_ITEM_SAVED'));
}

/**
 * Cancels an edit operation
 * @param string The current url option
 */
function cancelNewsletter( )
{
	global $mainframe;
	$database  =& JFactory::getDBO();
	$Itemid    = JRequest::getInt('Itemid');
	$option    = JRequest::getVar('option');
	$row = new josCommunicator( $database );
	$row->bind( $_POST );
	$row->checkin();
	$mainframe->redirect( 'index.php?option='.$option.'&Itemid='.$Itemid);
}

/**
 * Deletes one or more records
 * @param array An array of unique category id numbers
 * @param string The current url option
 */
function removeNewsletter( $id )
{
	global $mainframe;
	$database =& JFactory::getDBO();
	$Itemid = JRequest::getInt('Itemid');
	$option = JRequest::getVar('option');

	$item = new josCommunicator( $database );
	if (!$item->delete( $id )) {
		echo "<script type=\"text/javascript\"> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
	}
	else {
		$mainframe->redirect( 'index.php?option='.$option.'&Itemid='.$Itemid);
	}
}